/*
 * TalkPane.java
 *
 * Created on 2009-12-27, 00:49:54
 */

package gui;

//import chord.ChordTools;
import gui.observer.ConversationObserver;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import net.ConversationService;

/**
 *
 * @author Paweł Kopiczko
 */
public class TalkPane extends javax.swing.JPanel {
    private ConversationService conversationService;
    private java.awt.event.KeyListener keyListener;
    private boolean keyListenerAdded = false;
    private int index;

    /** Creates new form TalkPane */
    public TalkPane(Socket socket, int index, String username) throws IOException {
        this.index = index;
        initComponents();
        initAdapters();
        initConversationService(socket);
        conversationService.sendHello(username);
    }

    public void write(String text) {
        jTextAreaReading.append(text + "\n");
        jTextAreaReading.setCaretPosition(jTextAreaReading.getText().length());
    }

    public void close() throws IOException {
        conversationService.sendBye();
        conversationService.closeConnection();
    }

    private void sendMessage() {
        String messageText = jTextAreaTyping.getText();
        if (messageText.equals("") || messageText.equals(" ")) {
            jTextAreaReading.append("\n\nNo message to send!\n");
            return;
        }
        conversationService.sendText(messageText);
//        jTextAreaReading.set
        jTextAreaReading.setForeground(new java.awt.Color(51, 51, 255));
        jTextAreaReading.append(messageText + "\n");
        jTextAreaReading.setForeground(new java.awt.Color(0, 0, 0));
        jTextAreaReading.setCaretPosition(jTextAreaReading.getText().length());
        jTextAreaTyping.setText("");
    }

    private void initAdapters() {
        keyListener = new KeyListener() {
            public void keyTyped(KeyEvent e) { }
            public void keyPressed(KeyEvent e) { }
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    try {
                        jTextAreaTyping.setText(jTextAreaTyping.getText(0, jTextAreaTyping.getText().length() - 1));
                    } catch (BadLocationException ex) {
                        Logger.getLogger(TalkPane.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    sendMessage();
                }
            }
        };
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaReading = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextAreaTyping = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jToggleButton1 = new javax.swing.JToggleButton();

        setDoubleBuffered(false);

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane1.setAutoscrolls(true);
        jScrollPane1.setDoubleBuffered(true);
        jScrollPane1.setNextFocusableComponent(jTextAreaTyping);
        jScrollPane1.setPreferredSize(new java.awt.Dimension(200, 200));

        jTextAreaReading.setColumns(20);
        jTextAreaReading.setEditable(false);
        jTextAreaReading.setFont(new java.awt.Font("Monospaced", 1, 12)); // NOI18N
        jTextAreaReading.setForeground(new java.awt.Color(51, 51, 255));
        jTextAreaReading.setRows(5);
        jScrollPane1.setViewportView(jTextAreaReading);

        jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane2.setDoubleBuffered(true);

        jTextAreaTyping.setColumns(20);
        jTextAreaTyping.setFont(new java.awt.Font("Monospaced", 0, 12));
        jTextAreaTyping.setRows(5);
        jTextAreaTyping.setMaximumSize(new java.awt.Dimension(2147483647, 62));
        jScrollPane2.setViewportView(jTextAreaTyping);

        jButton1.setText("Send");
        jButton1.setDoubleBuffered(true);
        jButton1.setMinimumSize(new java.awt.Dimension(27, 23));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jToggleButton1.setText("Enter");
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToggleButton1))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jToggleButton1)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        sendMessage();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        if (keyListenerAdded) {
            jTextAreaTyping.removeKeyListener(keyListener);
            keyListenerAdded = false;
            return;
        }
        jTextAreaTyping.addKeyListener(keyListener);
        keyListenerAdded = true;
    }//GEN-LAST:event_jToggleButton1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextAreaReading;
    private javax.swing.JTextArea jTextAreaTyping;
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration//GEN-END:variables

    public int getIndex() {
        return index;
    }

    private void initConversationService(Socket socket) throws IOException {
        conversationService = new ConversationService(socket);
        conversationService.addObserver(new ConversationObserver(this));
        new Thread(conversationService).start();
//        conversationService.sendHello(user.UserTools.GetName());
    }

}
